﻿using System;
using UnityEngine;
using UnityEngine.Networking;

namespace GameFrameWork
{
    public class AssetBundleAwaiter : IAwaiter<AssetBundleAwaiter, AssetBundle>, IDisposable
    {
        public AssetBundle Bundle { get; private set; }
        public bool IsCompleted { get; set; }

        public string Url { get; private set; }

        protected Action continuation = null;

        public UnityWebRequest req { get; private set; }

        public AssetBundleAwaiter(string url)
        {
            Url = url;
        }

        public AssetBundle GetResult()
        {
            return Bundle;
        }
        public AssetBundleAwaiter GetAwaiter()
        {
            return this;
        }

        public void OnCompleted(Action continuation)
        {
            //Debug.Log($"[AssetBundleAwaiter] {Url}, {IsCompleted}, {Bundle}, {GetHashCode()}");
            if (IsCompleted || Bundle != null)
            {
                continuation?.Invoke();
                return;
            }
            this.continuation += continuation;
            if (req == null)
            {
                req = UnityWebRequestAssetBundle.GetAssetBundle(Utility.Path.GetRemotePath(Url));
                var op = req.SendWebRequest();
                op.completed += OnFinish;
            }
        }

        private void OnFinish(AsyncOperation pp)
        {
            IsCompleted = true;
            var abHandler = req?.downloadHandler as DownloadHandlerAssetBundle;
            Bundle = abHandler?.assetBundle;
            continuation?.Invoke();
            continuation = null;
            req?.Dispose();
            req = null;
        }

        public void Dispose()
        {
            IsCompleted = true;
            req?.Dispose();
            req = null;
            Bundle = null;
            continuation?.Invoke();
            continuation = null;
        }
    }
}


